<!--
 * @Description:
 * @Version:
 * @Autor: ps
 * @Date: 2022-09-08 11:43:43
 * @LastEditors: ps
 * @LastEditTime: 2022-09-13 18:22:05
-->
<template>
  <div class="barChart">
    <div :id="id" :style="{ height: height + 'px', width: width }"></div>
  </div>
</template>

<script>
import echarts from "@/utils/lib/echarts";
import { BarChart } from "echarts/charts";
import colorConst from "@/utils/custom-color.js";
echarts.use([BarChart]);
export default {
  name: "portrayaLineChat",
  props: {
    // 折线图数据
    id: {
      type: String,
      default: "portrayalChartA",
    },
    data: {
      type: Array,
      default: [],
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: Number,
      default: 360,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    data: {
      handler(val) {
        if (val) {
          this.chartDes();
          this.barCharts(val);
        }
      },
      deep: true,
      immediate: false,
    },
  },
  beforeDestroy() {
    this.chartDes();
  },
  methods: {
    chartDes() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    barCharts(data) {
      let nameArr = [];
      let seriesData = [];
      data.forEach((element) => {
        seriesData.push(element.count);
        nameArr.push(element.deptName);
      });
      let option = {
        color: colorConst.customColorarr,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
        },
        yAxis: {
          type: "category",
          data: nameArr,
        },
        series: {
          data: seriesData,
          type: "bar",
          showBackground: true,
          backgroundStyle: {
            color: "rgba(180, 180, 180, 0.2)",
          },
        },
      };
      this.initChart(this.id, option);
    },
    initChart(id, options) {
      this.chart = echarts.init(document.getElementById(id));
      this.chart.setOption(options);
      window.addEventListener("resize", () => {
        if (this.chart) {
          this.chart.resize();
        }
      });
    },
  },
};
</script>
